package com.moss.street.market;
/*
 * Created on November 25, 2011.
 * This is a highly modified version of the code presented in the tutorial
 * "Build Web applications with Eclipse, WTP, and Derby" by Susan L. Cline at
 * http://www.ibm.com/developerworks/data/library/techarticle/dm-0509cline/
 */

import java.io.IOException;
import java.sql.Connection;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;


/**
 * A controller servlet for the Login.jsp and Register.jsp view.
 * 
 * @author drusk
 * 
 */
public class LoginServlet extends HttpServlet implements Servlet {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpSerevletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String newUser = request.getParameter("newuser"); // set by checkbox in Login.jsp
		String loggedOut = request.getParameter("loggedOut");

		String lastName = request.getParameter("lastname");
		String firstName = request.getParameter("firstname");
		String contactInfo = request.getParameter("contactinfo");
		String emailAddress = request.getParameter("emailaddress");
		
		Connection conn = DerbyDatabase.getConnInstance();

		// if the post came with newuser set, then we will need to add the
		// user to the database, otherwise look up the user in the DB

		boolean validUser = false;
		boolean haveUserInfo = (username != null && !username.isEmpty() &&
				password != null && !password.isEmpty() &&
				lastName != null && !lastName.isEmpty() &&
				firstName != null && !firstName.isEmpty() &&
				contactInfo != null && !contactInfo.isEmpty() &&
				emailAddress != null && !emailAddress.isEmpty() &&
				emailAddress.contains("@") && emailAddress.contains("."));

		// if the user is not new, look up the username and password
		// in the MSS.USERS table
		if (username != null && !username.isEmpty() &&
				password != null && !password.isEmpty() &&
				(newUser == null || newUser.equals(""))) {
			UsersBean[] userResults = DerbyDatabase.accountQuery(conn, username, password);

			// if the query was successful one row should be returned
			if (userResults.length == 1) {
				validUser = true;
			}
		}
		// the user is new.  See whether the username has been taken.
		// If it is available get user information.
		if (newUser != null && username != null && !username.isEmpty() && !haveUserInfo) {
			UsersBean[] userResults = DerbyDatabase.accountQuery(conn, username);
			// if the username is available, no rows should be returned
			if (userResults == null || userResults.length == 0) {
				validUser = true;
				request.getSession().setAttribute("username", username);
				request.getSession().setAttribute("password", password);
				getServletContext().getRequestDispatcher("/Register.jsp").forward(
						request, response);
				return;
			}
		}
		// New user registration form is valid.
		// Insert the username, password, etc. into the MSS.USERS table
		else if (newUser != null && haveUserInfo) {
			int numRows = DerbyDatabase.accountUpdate(conn, username, password,
					lastName, firstName, "N", emailAddress, contactInfo);
			if (numRows == 1) {
				validUser = true;
			}
		}

		Cookie cookie = null;

		if (validUser) {
			// the username and password are in the database
			
			//get rid of login_failed attribute if it was set
			if (request.getSession().getAttribute("login_failed") != null) {
				request.getSession().removeAttribute("login_failed");
			}
			
			// For added security get rid of staffmember attribute if it was set.
			// This is important if staff members use web browsers on public
			// workstations.
			if (request.getSession().getAttribute("staffmember") != null) {
				request.getSession().removeAttribute("staffmember");
			}
			
			// set a cookie and proceed to the welcome page
			Cookie[] cookies = request.getCookies();
			// boolean newCookie = false;

			if (cookies != null) {
				for (int i = 0; i < cookies.length; i++) {
					// if they already have a mossStreetMarketCookie they
					// have been here before
					if (cookies[i].getName().equals("mossStreetMarketCookie")) {
						cookie = cookies[i];
					}
				}
			}
			if (cookie == null) {
				// newCookie = true;
				cookie = new Cookie("mossStreetMarketCookie", getNextCookieValue());
				// by setting this path to / this will send the cookie
				// back to all pages, not just this servlet mapping
				cookie.setPath("/");
				//just want session cookie
				//cookie.setMaxAge(60*60*24*7); // one week
				response.addCookie(cookie);
			}
			
			// put the username in the session object
			request.getSession().setAttribute("username", username);
			if (DerbyDatabase.isStaffMember(conn, username, password)) {
				request.getSession().setAttribute("staffmember", "true");
				getServletContext().getRequestDispatcher("/Admin.jsp")
				.forward(request, response);
			} else {
				getServletContext().getRequestDispatcher("/Welcome.jsp")
				.forward(request, response);
			}
		} else {
			
			// otherwise the user was not in the database, or another user
			// had that name already.
			if (newUser != null) {
				// send them back to register as a new user
				String message = "That username has already been taken.  Please select another.";
				request.getSession().setAttribute("login_failed", message);
				getServletContext().getRequestDispatcher("/Login.jsp")
						.forward(request, response);
			} else if (loggedOut != null) {
				getServletContext().getRequestDispatcher("/Login.jsp").forward(
						request, response);
			} else {
				// make them login as a valid user who mistyped the password
				String message = "The name and user you attempted to login with do not exist in the database or you mistyped your password.  Please try again.";
				request.getSession().setAttribute("login_failed", message);
				getServletContext().getRequestDispatcher("/Login.jsp").forward(
						request, response);
			}

		}

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	private String getNextCookieValue() {
		return (new java.lang.Long(new java.util.Date().getTime()).toString());
	}

}
